<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第3章-后置处理器和Bean生命周期 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前面讲了Bean工厂后置处理器，这一篇开始讲Bean后置处理器">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第3章-后置处理器和Bean生命周期">
<meta property="og:url" content="https://imlql.cn/post/66c146e7.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="前面讲了Bean工厂后置处理器，这一篇开始讲Bean后置处理器">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2021-12-31T16:01:02.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.049Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/66c146e7"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第3章-后置处理器和Bean生命周期',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第3章-后置处理器和Bean生命周期</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-31T16:01:02.000Z" title="发表于 2022-01-01 00:01:02">2022-01-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.049Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">7.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>35分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第3章-后置处理器和Bean生命周期"><a href="#第3章-后置处理器和Bean生命周期" class="headerlink" title="第3章-后置处理器和Bean生命周期"></a>第3章-后置处理器和Bean生命周期</h1><h2 id="再来看一下我们的测试类"><a href="#再来看一下我们的测试类" class="headerlink" title="再来看一下我们的测试类"></a>再来看一下我们的测试类</h2><blockquote>
<p>为了分析后面的，测试类有些许变动</p>
</blockquote>
<h3 id="MyBeanPostProcessor"><a href="#MyBeanPostProcessor" class="headerlink" title="MyBeanPostProcessor"></a>MyBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanPostProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...postProcessAfterInitialization...&quot;</span> + bean + <span class="string">&quot;==&gt;&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...postProcessBeforeInitialization...&quot;</span> + bean + <span class="string">&quot;==&gt;&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> bean; <span class="comment">// new Object();</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyInstantiationAwareBeanPostProcessor"><a href="#MyInstantiationAwareBeanPostProcessor" class="headerlink" title="MyInstantiationAwareBeanPostProcessor"></a>MyInstantiationAwareBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyInstantiationAwareBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">InstantiationAwareBeanPostProcessor</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyInstantiationAwareBeanPostProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125; <span class="comment">//初始化之前进行后置处理，Spring留给我们给这个组件创建对象的回调。</span></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName); <span class="comment">//if(class.isAssFrom(Cat.class))&#123;return new Dog()&#125;</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>; <span class="comment">//如果我们自己创建了对象返回。Spring则不会帮我们创建对象，用我们自己创建的对象？ 我们创建的这个对象，Spring会保存单实例？还是每次getBean都调到我们这里创建一个新的？</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">postProcessAfterInstantiation</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName); <span class="comment">//提前改变一些Spring不管的bean里面的属性</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">true</span>; <span class="comment">//返回false则bean的赋值全部结束</span></span><br><span class="line">   &#125;  <span class="comment">//解析自定义注解进行属性值注入；pvs 封装了所有的属性信息。</span></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> BeansException </span>&#123; </span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessProperties=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyMergedBeanDefinitionPostProcessor"><a href="#MyMergedBeanDefinitionPostProcessor" class="headerlink" title="MyMergedBeanDefinitionPostProcessor"></a>MyMergedBeanDefinitionPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyMergedBeanDefinitionPostProcessor</span> <span class="keyword">implements</span> <span class="title">MergedBeanDefinitionPostProcessor</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyMergedBeanDefinitionPostProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> bean; <span class="comment">//null</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessMergedBeanDefinition</span><span class="params">(RootBeanDefinition beanDefinition, Class&lt;?&gt; beanType, String beanName)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=&gt;&quot;</span> + beanName + <span class="string">&quot;--&quot;</span> + beanType + <span class="string">&quot;---&quot;</span> + beanDefinition);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">resetBeanDefinition</span><span class="params">(String beanName)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...resetBeanDefinition..&quot;</span> + beanName);</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MySmartInstantiationAwareBeanPostProcessor"><a href="#MySmartInstantiationAwareBeanPostProcessor" class="headerlink" title="MySmartInstantiationAwareBeanPostProcessor"></a>MySmartInstantiationAwareBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span>   <span class="comment">//bean进行代理增强期间进行使用</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySmartInstantiationAwareBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">SmartInstantiationAwareBeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MySmartInstantiationAwareBeanPostProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;  <span class="comment">//预测bean的类型，最后一次改变组件类型。</span></span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> Class&lt;?&gt; predictBeanType(Class&lt;?&gt; beanClass, String beanName) <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...predictBeanType=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//返回我们要使用的构造器候选列表</span></span><br><span class="line">   <span class="keyword">public</span> Constructor&lt;?&gt;[] determineCandidateConstructors(Class&lt;?&gt; beanClass, String beanName)</span><br><span class="line">         <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">      <span class="comment">//返回一个我们指定的构造器</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//返回早期的bean引用</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">getEarlyBeanReference</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="MyBeanFactoryPostProcessor"><a href="#MyBeanFactoryPostProcessor" class="headerlink" title="MyBeanFactoryPostProcessor"></a>MyBeanFactoryPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * BeanFactory的后置处理器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanFactoryPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanFactoryPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanFactoryPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanFactoryPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;BeanFactoryPostProcessor....postProcessBeanFactory==&gt;&quot;</span>+beanFactory);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyBeanDefinitionRegistryPostProcessor"><a href="#MyBeanDefinitionRegistryPostProcessor" class="headerlink" title="MyBeanDefinitionRegistryPostProcessor"></a>MyBeanDefinitionRegistryPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanDefinitionRegistryPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanDefinitionRegistryPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanDefinitionRegistryPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="meta">@Override</span>  <span class="comment">//紧接着执行</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span>  <span class="comment">//先执行的</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...&quot;</span>);</span><br><span class="line">      <span class="comment">//增强bean定义信息的注册中心，比如自己注册组件</span></span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Cat"><a href="#Cat" class="headerlink" title="Cat"></a>Cat</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> <span class="keyword">implements</span> <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;cat被创建了...&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="meta">@Value(&quot;$&#123;JAVA_HOME&#125;&quot;)</span> <span class="comment">//自动赋值功能</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;cat....setName正在赋值调用....&quot;</span>);</span><br><span class="line">		<span class="keyword">this</span>.name = name;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//注解怎么定义这个是初始化方法？</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> name;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;CatInitializingBean..afterPropertiesSet...&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="beans2-xml"><a href="#beans2-xml" class="headerlink" title="beans2.xml"></a>beans2.xml</h3><figure class="highlight"><table><tr><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span><br><span class="line">	   xmlns:xsi=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="line">	   xmlns:context=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span><br><span class="line">	   xsi:schemaLocation=<span class="string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">	&lt;context:component-scan base-<span class="keyword">package</span>=<span class="string">&quot;cn.imlql.spring.processor&quot;</span>/&gt;</span><br><span class="line"></span><br><span class="line">	&lt;bean <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;cn.imlql.spring.bean.Cat&quot;</span> id=<span class="string">&quot;cat&quot;</span>/&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<h3 id="MainTest"><a href="#MainTest" class="headerlink" title="MainTest"></a>MainTest</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		ClassPathXmlApplicationContext context = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;beans2.xml&quot;</span>);</span><br><span class="line">		Person bean = context.getBean(Person.class);</span><br><span class="line">		System.out.println(bean);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h2 id="继续Bean生命周期"><a href="#继续Bean生命周期" class="headerlink" title="继续Bean生命周期"></a>继续Bean生命周期</h2><h3 id="流程图-Bean生命周期与后置处理器"><a href="#流程图-Bean生命周期与后置处理器" class="headerlink" title="流程图-Bean生命周期与后置处理器"></a>流程图-Bean生命周期与后置处理器</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/Bean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E4%B8%8E%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8.png">

<h3 id="BeanPostProcessor-执行无参构造"><a href="#BeanPostProcessor-执行无参构造" class="headerlink" title="BeanPostProcessor-执行无参构造"></a>BeanPostProcessor-执行无参构造</h3><blockquote>
<p>前面两个工厂后置处理器执行完之后，接下来就是我们的Bean后置处理器，第一个执行的就是BeanPostProcessor</p>
</blockquote>
<h4 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929142257774.png"/>

<h4 id="AbstractApplicationContext-registerBeanPostProcessors-注册Bean后置处理器"><a href="#AbstractApplicationContext-registerBeanPostProcessors-注册Bean后置处理器" class="headerlink" title="AbstractApplicationContext#registerBeanPostProcessors()注册Bean后置处理器"></a>AbstractApplicationContext#registerBeanPostProcessors()注册Bean后置处理器</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerBeanPostProcessors</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, <span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="PostProcessorRegistrationDelegate-registerBeanPostProcessors"><a href="#PostProcessorRegistrationDelegate-registerBeanPostProcessors" class="headerlink" title="PostProcessorRegistrationDelegate#registerBeanPostProcessors()"></a>PostProcessorRegistrationDelegate#registerBeanPostProcessors()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">registerBeanPostProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//获取到容器中所有的 BeanPostProcessor； Bean的后置处理器</span></span><br><span class="line">   String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Register BeanPostProcessorChecker that logs an info message when</span></span><br><span class="line">   <span class="comment">// a bean is created during BeanPostProcessor instantiation, i.e. when</span></span><br><span class="line">   <span class="comment">// a bean is not eligible for getting processed by all BeanPostProcessors.</span></span><br><span class="line">   <span class="keyword">int</span> beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + <span class="number">1</span> + postProcessorNames.length;</span><br><span class="line">   beanFactory.addBeanPostProcessor(<span class="keyword">new</span> BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Separate between BeanPostProcessors that implement PriorityOrdered,</span></span><br><span class="line">   <span class="comment">// Ordered, and the rest.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; priorityOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;BeanPostProcessor&gt; internalPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; orderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; nonOrderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">      <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) &#123;  <span class="comment">//获取所有实现了 PriorityOrdered 的 BeanPostProcessor</span></span><br><span class="line">         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);</span><br><span class="line">         priorityOrderedPostProcessors.add(pp);</span><br><span class="line">         <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">            internalPostProcessors.add(pp);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, Ordered.class)) &#123;</span><br><span class="line">         orderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         nonOrderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//首先，注册所有的实现了 PriorityOrdered 的 BeanPostProcessor ；  First, register the BeanPostProcessors that implement PriorityOrdered.</span></span><br><span class="line">   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">//接下来，注册所有的实现了 Ordered 的 BeanPostProcessor  Next, register the BeanPostProcessors that implement Ordered.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; orderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(orderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String ppName : orderedPostProcessorNames) &#123;</span><br><span class="line">      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);</span><br><span class="line">      orderedPostProcessors.add(pp);</span><br><span class="line">      <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">         internalPostProcessors.add(pp);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   sortPostProcessors(orderedPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, orderedPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 最后，注册所有普通的 BeanPostProcessor ；Now, register all regular BeanPostProcessors.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; nonOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(nonOrderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String ppName : nonOrderedPostProcessorNames) &#123;</span><br><span class="line">      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); <span class="comment">//从容器中获取这个组件</span></span><br><span class="line">      nonOrderedPostProcessors.add(pp);</span><br><span class="line">      <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">         internalPostProcessors.add(pp);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);<span class="comment">//所谓的注册其实就是保存到一个Map里面，后续用的时候可以直接拿</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">// Finally, re-register all internal BeanPostProcessors.</span></span><br><span class="line">   sortPostProcessors(internalPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, internalPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Re-register post-processor for detecting inner beans as ApplicationListeners,</span></span><br><span class="line">   <span class="comment">// moving it to the end of the processor chain (for picking up proxies etc).</span></span><br><span class="line">   beanFactory.addBeanPostProcessor(<span class="keyword">new</span> ApplicationListenerDetector(applicationContext));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>Bean工厂后置处理器调用的是<code>invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory , List&lt;BeanFactoryPostProcessor&gt; )</code></li>
<li>Bean后置处理器调用的是<code>registerBeanPostProcessors(ConfigurableListableBeanFactory , AbstractApplicationContext )</code></li>
</ul>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929144115434.png"/>



<h3 id="InstantiationAwareBeanPostProcessor-执行无参构造"><a href="#InstantiationAwareBeanPostProcessor-执行无参构造" class="headerlink" title="InstantiationAwareBeanPostProcessor-执行无参构造"></a>InstantiationAwareBeanPostProcessor-执行无参构造</h3><blockquote>
<ol>
<li>BeanPostProcessor执行顺序和BeanFactoryPostProcessor有点不一样</li>
<li>BeanFactoryPostProcessor是先执行完每一个的无参构造和实现的几个方法，再去执行下一个BeanFactoryPostProcessor</li>
<li>BeanPostProcessor是先执行所有BeanPostProcessor的无参构造，再执行所有BeanPostProcessor实现的方法。</li>
</ol>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929145612361.png"/>

<h3 id="MergedBeanDefinitionPostProcessor-执行无参构造"><a href="#MergedBeanDefinitionPostProcessor-执行无参构造" class="headerlink" title="MergedBeanDefinitionPostProcessor-执行无参构造"></a>MergedBeanDefinitionPostProcessor-执行无参构造</h3><p>同上</p>
<h3 id="SmartInstantiationAwareBeanPostProcessor-执行无参构造"><a href="#SmartInstantiationAwareBeanPostProcessor-执行无参构造" class="headerlink" title="SmartInstantiationAwareBeanPostProcessor-执行无参构造"></a>SmartInstantiationAwareBeanPostProcessor-执行无参构造</h3><p>同上</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929150155334.png"/>





<h3 id="SmartInstantiationAwareBeanPostProcessor-执行predictBeanType方法"><a href="#SmartInstantiationAwareBeanPostProcessor-执行predictBeanType方法" class="headerlink" title="SmartInstantiationAwareBeanPostProcessor-执行predictBeanType方法"></a>SmartInstantiationAwareBeanPostProcessor-执行predictBeanType方法</h3><h4 id="Debug调用栈-1"><a href="#Debug调用栈-1" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929160714133.png"/>



<h4 id="AbstractApplicationContext-refresh"><a href="#AbstractApplicationContext-refresh" class="headerlink" title="AbstractApplicationContext#refresh()"></a>AbstractApplicationContext#refresh()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>  <span class="comment">//容器刷新的十二大步。</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">      StartupStep contextRefresh = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.refresh&quot;</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Prepare this context for refreshing.</span></span><br><span class="line">      prepareRefresh();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">      <span class="comment">// 工厂创建：BeanFactory第一次开始创建的时候,有xml解析逻辑。</span></span><br><span class="line">      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Prepare the bean factory for use in this context.</span></span><br><span class="line">      prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">// Allows post-processing of the bean factory in context subclasses.</span></span><br><span class="line">         postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">         StartupStep beanPostProcess = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.beans.post-process&quot;</span>);</span><br><span class="line">         <span class="comment">//工厂增强：执行所有的BeanFactory后置增强器；利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context.</span></span><br><span class="line">         invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="comment">//注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.</span></span><br><span class="line">         registerBeanPostProcessors(beanFactory);</span><br><span class="line">         beanPostProcess.end();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Initialize message source for this context.</span></span><br><span class="line">         initMessageSource();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Initialize event multicaster for this context.</span></span><br><span class="line">         initApplicationEventMulticaster();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Initialize other special beans in specific context subclasses.</span></span><br><span class="line">         onRefresh();</span><br><span class="line"></span><br><span class="line">         <span class="comment">//注册监听器，从容器中获取所有的ApplicationListener； Check for listener beans and register them.</span></span><br><span class="line">         registerListeners();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">         <span class="comment">//bean创建；完成 BeanFactory 初始化。（工厂里面所有的组件都好了）</span></span><br><span class="line">         finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Last step: publish corresponding event.</span></span><br><span class="line">         finishRefresh();</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">         <span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">            logger.warn(<span class="string">&quot;Exception encountered during context initialization - &quot;</span> +</span><br><span class="line">                  <span class="string">&quot;cancelling refresh attempt: &quot;</span> + ex);</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Destroy already created singletons to avoid dangling resources.</span></span><br><span class="line">         destroyBeans();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Reset &#x27;active&#x27; flag.</span></span><br><span class="line">         cancelRefresh(ex);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Propagate exception to caller.</span></span><br><span class="line">         <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">finally</span> &#123;</span><br><span class="line">         <span class="comment">// Reset common introspection caches in Spring&#x27;s core, since we</span></span><br><span class="line">         <span class="comment">// might not ever need metadata for singleton beans anymore...</span></span><br><span class="line">         resetCommonCaches();</span><br><span class="line">         contextRefresh.end();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerListeners</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Register statically specified listeners first.</span></span><br><span class="line">   <span class="keyword">for</span> (ApplicationListener&lt;?&gt; listener : getApplicationListeners()) &#123;</span><br><span class="line">      getApplicationEventMulticaster().addApplicationListener(listener);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Do not initialize FactoryBeans here: We need to leave all regular beans</span></span><br><span class="line">   <span class="comment">// uninitialized to let post-processors apply to them! 获取ApplicationListener在ioc容器中注册的bean的名字</span></span><br><span class="line">   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">   <span class="keyword">for</span> (String listenerBeanName : listenerBeanNames) &#123;</span><br><span class="line">      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); <span class="comment">//获取所有的容器中的监听器，并保存他们的名字</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Publish early application events now that we finally have a multicaster...</span></span><br><span class="line">   Set&lt;ApplicationEvent&gt; earlyEventsToProcess = <span class="keyword">this</span>.earlyApplicationEvents;</span><br><span class="line">   <span class="keyword">this</span>.earlyApplicationEvents = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (!CollectionUtils.isEmpty(earlyEventsToProcess)) &#123;</span><br><span class="line">      <span class="keyword">for</span> (ApplicationEvent earlyEvent : earlyEventsToProcess) &#123;</span><br><span class="line">         getApplicationEventMulticaster().multicastEvent(earlyEvent);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在调用registerListeners()的时候，竟然进入到了我们的后置处理器逻辑，我们接着往后看</p>
<h4 id="DefaultListableBeanFactory-doGetBeanNamesForType-获取某一个组件在容器中的名字"><a href="#DefaultListableBeanFactory-doGetBeanNamesForType-获取某一个组件在容器中的名字" class="headerlink" title="DefaultListableBeanFactory#doGetBeanNamesForType()获取某一个组件在容器中的名字"></a>DefaultListableBeanFactory#doGetBeanNamesForType()获取某一个组件在容器中的名字</h4><p>调过一些不重要的调用，逻辑到了这里</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="comment">//获取某一个组件在容器中的名字。</span></span><br><span class="line"><span class="keyword">private</span> String[] doGetBeanNamesForType(ResolvableType type, <span class="keyword">boolean</span> includeNonSingletons, <span class="keyword">boolean</span> allowEagerInit) &#123;</span><br><span class="line">	List&lt;String&gt; result = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Check all bean definitions. 因为Spring没有直接保存class--bean名字的对应信息，只能遍历所有的beanname，拿出他们beanname的定义信息，再看是否我指定的类型。</span></span><br><span class="line">	<span class="keyword">for</span> (String beanName : <span class="keyword">this</span>.beanDefinitionNames) &#123;</span><br><span class="line">		<span class="comment">// Only consider bean as eligible if the bean name is not defined as alias for some other bean.</span></span><br><span class="line">		<span class="keyword">if</span> (!isAlias(beanName)) &#123; <span class="comment">//判断是否别名</span></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);</span><br><span class="line">				<span class="comment">// Only check bean definition if it is complete.</span></span><br><span class="line">				<span class="keyword">if</span> (!mbd.isAbstract() &amp;&amp; (allowEagerInit ||</span><br><span class="line">						(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &amp;&amp;</span><br><span class="line">								!requiresEagerInitForType(mbd.getFactoryBeanName()))) &#123;</span><br><span class="line">					<span class="keyword">boolean</span> isFactoryBean = isFactoryBean(beanName, mbd); <span class="comment">//是否FactoryBean</span></span><br><span class="line">					BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();</span><br><span class="line">					<span class="keyword">boolean</span> matchFound = <span class="keyword">false</span>;</span><br><span class="line">					<span class="keyword">boolean</span> allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));</span><br><span class="line">					<span class="keyword">boolean</span> isNonLazyDecorated = (dbd != <span class="keyword">null</span> &amp;&amp; !mbd.isLazyInit());</span><br><span class="line">					<span class="keyword">if</span> (!isFactoryBean) &#123;</span><br><span class="line">						<span class="keyword">if</span> (includeNonSingletons || isSingleton(beanName, mbd, dbd)) &#123;</span><br><span class="line">							matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); <span class="comment">//是否类型匹配？</span></span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">else</span> &#123;</span><br><span class="line">						<span class="keyword">if</span> (includeNonSingletons || isNonLazyDecorated ||</span><br><span class="line">								(allowFactoryBeanInit &amp;&amp; isSingleton(beanName, mbd, dbd))) &#123;</span><br><span class="line">							matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);</span><br><span class="line">						&#125;</span><br><span class="line">						<span class="keyword">if</span> (!matchFound) &#123;</span><br><span class="line">							<span class="comment">// In case of FactoryBean, try to match FactoryBean instance itself next.</span></span><br><span class="line">							beanName = FACTORY_BEAN_PREFIX + beanName;</span><br><span class="line">							matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">if</span> (matchFound) &#123;</span><br><span class="line">						result.add(beanName);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">               <span class="comment">// ......</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> StringUtils.toStringArray(result);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>下面是容器中现在有的bean定义信息，但是这些bean不一定都创建好了。</li>
<li>Spring在这里是想要按照类型去容器中去找组件，在这里就是想找ApplicationListener.class类型的组件。但是Spring中只存储了BeanName=&gt;BeanType的对应关系（BeanDefinitions），没有存BeanType=&gt;BeanName的对应关系。<ol>
<li>所以在这里只能遍历循环beanDefinitionNames</li>
<li>通过beanName再去BeanDefinitions拿beanType</li>
<li>判断是不是想要的类型。</li>
</ol>
</li>
<li>这里有没有优化空间，再存一个BeanType=&gt;BeanName的对应关系？但是这样的关系是一对多的，同一个BeanType下可能有多个beanName，Spring可能是考虑到空间成本，没有这样弄。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929163852056.png"/>



<h4 id="AbstractBeanFactory-isTypeMatch"><a href="#AbstractBeanFactory-isTypeMatch" class="headerlink" title="AbstractBeanFactory#isTypeMatch()"></a>AbstractBeanFactory#isTypeMatch()</h4><ol>
<li>有一个小细节，在debug的时候我们发现这里，只有Cat类进入到了后续判断，为什么上面的其它9个类没有进入后续逻辑呢？</li>
</ol>
<p>这里是因为其它9个对象都已经在之前创建好了对象，只有Cat还没有创建对象。Spring在这里给我们一个机会，在对象创建之前，我们可以最后一次决定Cat的类型。什么意思？往后看</p>
<ol start="2">
<li>我们来看看此时单例池里有哪些对象</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929170557025.png" />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isTypeMatch</span><span class="params">(String name, ResolvableType typeToMatch, <span class="keyword">boolean</span> allowFactoryBeanInit)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> NoSuchBeanDefinitionException </span>&#123;</span><br><span class="line"></span><br><span class="line">   String beanName = transformedBeanName(name);</span><br><span class="line">   <span class="keyword">boolean</span> isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 检查是否已经有这个beanName的单例对象，有了直接用对象的Class，没有可以最后一次决定这个组件的类型；SmartInstantiationAwareBeanPostProcessor.predictBeanType() Check manually registered singletons.</span></span><br><span class="line">   Object beanInstance = getSingleton(beanName, <span class="keyword">false</span>);</span><br><span class="line">   <span class="keyword">if</span> (beanInstance != <span class="keyword">null</span> &amp;&amp; beanInstance.getClass() != NullBean.class) &#123;</span><br><span class="line">      <span class="keyword">if</span> (beanInstance <span class="keyword">instanceof</span> FactoryBean) &#123;</span><br><span class="line">         <span class="keyword">if</span> (!isFactoryDereference) &#123;</span><br><span class="line">            Class&lt;?&gt; type = getTypeForFactoryBean((FactoryBean&lt;?&gt;) beanInstance);</span><br><span class="line">            <span class="keyword">return</span> (type != <span class="keyword">null</span> &amp;&amp; typeToMatch.isAssignableFrom(type));</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> typeToMatch.isInstance(beanInstance);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (!isFactoryDereference) &#123;</span><br><span class="line">         <span class="keyword">if</span> (typeToMatch.isInstance(beanInstance)) &#123;</span><br><span class="line">            <span class="comment">// Direct match for exposed instance?</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span> <span class="keyword">if</span> (typeToMatch.hasGenerics() &amp;&amp; containsBeanDefinition(beanName)) &#123;</span><br><span class="line">            <span class="comment">// ......</span></span><br><span class="line">            <span class="keyword">return</span> (resolvableType != <span class="keyword">null</span> &amp;&amp; typeToMatch.isAssignableFrom(resolvableType));</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> <span class="keyword">if</span> (containsSingleton(beanName) &amp;&amp; !containsBeanDefinition(beanName)) &#123;</span><br><span class="line">      <span class="comment">// null instance registered</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// No singleton instance found -&gt; check bean definition.</span></span><br><span class="line">   BeanFactory parentBeanFactory = getParentBeanFactory();</span><br><span class="line">   <span class="keyword">if</span> (parentBeanFactory != <span class="keyword">null</span> &amp;&amp; !containsBeanDefinition(beanName)) &#123;</span><br><span class="line">      <span class="comment">// No bean definition found in this factory -&gt; delegate to parent.</span></span><br><span class="line">      <span class="keyword">return</span> parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Retrieve corresponding bean definition.</span></span><br><span class="line">   RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);</span><br><span class="line">   BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Setup the types that we want to match against</span></span><br><span class="line">   Class&lt;?&gt; classToMatch = typeToMatch.resolve();</span><br><span class="line">   <span class="keyword">if</span> (classToMatch == <span class="keyword">null</span>) &#123;</span><br><span class="line">      classToMatch = FactoryBean.class;</span><br><span class="line">   &#125;</span><br><span class="line">   Class&lt;?&gt;[] typesToMatch = (FactoryBean.class == classToMatch ?</span><br><span class="line">         <span class="keyword">new</span> Class&lt;?&gt;[] &#123;classToMatch&#125; : <span class="keyword">new</span> Class&lt;?&gt;[] &#123;FactoryBean.class, classToMatch&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">// Attempt to predict the bean type</span></span><br><span class="line">   Class&lt;?&gt; predictedType = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (!isFactoryDereference &amp;&amp; dbd != <span class="keyword">null</span> &amp;&amp; isFactoryBean(beanName, mbd)) &#123;</span><br><span class="line">   		<span class="comment">// ...</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 通过后置处理器，可以返回自定义的类型 If we couldn&#x27;t use the target type, try regular prediction.</span></span><br><span class="line">   <span class="keyword">if</span> (predictedType == <span class="keyword">null</span>) &#123;</span><br><span class="line">      predictedType = predictBeanType(beanName, mbd, typesToMatch);</span><br><span class="line">      <span class="keyword">if</span> (predictedType == <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//......</span></span><br><span class="line">   <span class="comment">// If we don&#x27;t have a bean type, fallback to the predicted type</span></span><br><span class="line">   <span class="keyword">return</span> typeToMatch.isAssignableFrom(predictedType);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>预测BeanType是什么意思呢？因为每个组件都会经过我们自定义的方法，假设你现在有个Cat类，你可以在这里写个if判断。你可以让猫变成狗，有点类似于指鹿为马</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> Class&lt;?&gt; predictBeanType(Class&lt;?&gt; beanClass, String beanName) <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...predictBeanType=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">   <span class="keyword">if</span>(beanClass == Cat.class)&#123;</span><br><span class="line">     <span class="keyword">return</span> Dog.class;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="AbstractAutowireCapableBeanFactory-predictBeanType"><a href="#AbstractAutowireCapableBeanFactory-predictBeanType" class="headerlink" title="AbstractAutowireCapableBeanFactory#predictBeanType()"></a>AbstractAutowireCapableBeanFactory#predictBeanType()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">protected</span> Class&lt;?&gt; predictBeanType(String beanName, RootBeanDefinition mbd, Class&lt;?&gt;... typesToMatch) &#123;</span><br><span class="line">   Class&lt;?&gt; targetType = determineTargetType(beanName, mbd, typesToMatch);</span><br><span class="line">   <span class="comment">// Apply SmartInstantiationAwareBeanPostProcessors to predict the</span></span><br><span class="line">   <span class="comment">// eventual type after a before-instantiation shortcut.</span></span><br><span class="line">   <span class="keyword">if</span> (targetType != <span class="keyword">null</span> &amp;&amp; !mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">      <span class="keyword">boolean</span> matchingOnlyFactoryBean = typesToMatch.length == <span class="number">1</span> &amp;&amp; typesToMatch[<span class="number">0</span>] == FactoryBean.class;</span><br><span class="line">      <span class="keyword">for</span> (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) &#123;</span><br><span class="line">          <span class="comment">// 在这里调用我们自定义的predictBeanType,也就是MySmartInstantiationAwareBeanPostProcessor#predictBeanType</span></span><br><span class="line">         Class&lt;?&gt; predicted = bp.predictBeanType(targetType, beanName);<span class="comment">//还是可以理解为模板模式</span></span><br><span class="line">         <span class="keyword">if</span> (predicted != <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">               (!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) &#123;</span><br><span class="line">            <span class="keyword">return</span> predicted;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> targetType;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="此方法能做什么？"><a href="#此方法能做什么？" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><ol>
<li>SmartInstantiationAwareBeanPostProcessor起名为<strong>智能实例化感知后置处理器</strong>，smart也是聪明的意思，表示这是一个聪明的后置处理器</li>
<li>之所以这样起名，意思是我们可以实现这个接口然后实现它的方法，就可以告诉Spring：我们要使用的构造器候选列表。我们期望它是什么BeanType，甚至可以返回早期的bean引用（后面说）</li>
<li>那应用场景什么呢？<ol>
<li>当一个组件需要代理对象的时候，你如果返回原来的BeanType肯定是不对的，这时候这个功能就起作用了</li>
<li>还有我们可以在这里强制Spring全部使用有参构造器创建我们自己的Bean</li>
<li>bean进行代理增强期间这个接口用的比较多</li>
</ol>
</li>
<li>在Spring中只要调用了<code>doGetBeanNamesForType方法</code>或者<code>getBeanNamesForType方法</code>，就一定会经过SmartInstantiationAwareBeanPostProcessor的处理</li>
</ol>
<p>在此方法里为什么Cat会进来两次呢？往后面看</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929172115093.png" />

<h3 id="InstantiationAwareBeanPostProcessor-执行postProcessBeforeInstantiation方法"><a href="#InstantiationAwareBeanPostProcessor-执行postProcessBeforeInstantiation方法" class="headerlink" title="InstantiationAwareBeanPostProcessor-执行postProcessBeforeInstantiation方法"></a>InstantiationAwareBeanPostProcessor-执行postProcessBeforeInstantiation方法</h3><h4 id="Debug调用栈-2"><a href="#Debug调用栈-2" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929172554306.png"/>

<h4 id="AbstractApplicationContext-finishBeanFactoryInitialization-完成BeanFactory初始化"><a href="#AbstractApplicationContext-finishBeanFactoryInitialization-完成BeanFactory初始化" class="headerlink" title="AbstractApplicationContext#finishBeanFactoryInitialization()完成BeanFactory初始化"></a>AbstractApplicationContext#finishBeanFactoryInitialization()完成BeanFactory初始化</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finishBeanFactoryInitialization</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// 给工厂设置好 ConversionService【负责类型转换的组件服务】， Initialize conversion service for this context.</span></span><br><span class="line">   <span class="keyword">if</span> (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &amp;&amp;</span><br><span class="line">         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) &#123;</span><br><span class="line">      beanFactory.setConversionService(</span><br><span class="line">            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 注册一个默认的值解析器（&quot;$&#123;&#125;&quot;）  ；Register a default embedded value resolver if no BeanFactoryPostProcessor</span></span><br><span class="line">   <span class="comment">// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:</span></span><br><span class="line">   <span class="comment">// at this point, primarily for resolution in annotation attribute values.</span></span><br><span class="line">   <span class="keyword">if</span> (!beanFactory.hasEmbeddedValueResolver()) &#123;</span><br><span class="line">      beanFactory.addEmbeddedValueResolver(strVal -&gt; getEnvironment().resolvePlaceholders(strVal));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// LoadTimeWeaverAware；aspectj：加载时织入功能【aop】。 Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.</span></span><br><span class="line">   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, <span class="keyword">false</span>, <span class="keyword">false</span>);</span><br><span class="line">   <span class="keyword">for</span> (String weaverAwareName : weaverAwareNames) &#123;</span><br><span class="line">      getBean(weaverAwareName); <span class="comment">//从容器中获取组件，有则直接获取，没则进行创建</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Stop using the temporary ClassLoader for type matching.</span></span><br><span class="line">   beanFactory.setTempClassLoader(<span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Allow for caching all bean definition metadata, not expecting further changes.</span></span><br><span class="line">   beanFactory.freezeConfiguration();</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">   <span class="comment">//初始化所有的非懒加载的单实例Bean</span></span><br><span class="line">   beanFactory.preInstantiateSingletons();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>前面刚说过只要调用<code>getBeanNamesForType</code>，就会经过<code>SmartInstantiationAwareBeanPostProcessor</code>的处理。</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//注册监听器，从容器中获取所有的ApplicationListener； Check for listener beans and register them.</span></span><br><span class="line">registerListeners();</span><br><span class="line"></span><br><span class="line"><span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line"><span class="comment">//bean创建；完成 BeanFactory 初始化。（工厂里面所有的组件都好了）</span></span><br><span class="line">finishBeanFactoryInitialization(beanFactory);</span><br></pre></td></tr></table></figure>

<p>这两方法都调用了<code>getBeanNamesForType</code>，所以上面Cat会打印两次</p>
<ol start="2">
<li>上面我们也看了只有Cat的对象还没创建，还没初始化，所以下面就开始创建对象了。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929173103459.png"  />



<h4 id="AbstractAutowireCapableBeanFactory-createBean-创建Bean"><a href="#AbstractAutowireCapableBeanFactory-createBean-创建Bean" class="headerlink" title="AbstractAutowireCapableBeanFactory#createBean()创建Bean"></a>AbstractAutowireCapableBeanFactory#createBean()创建Bean</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      RootBeanDefinition mbdToUse = mbd;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Make sure bean class is actually resolved at this point, and</span></span><br><span class="line">      <span class="comment">// clone the bean definition in case of a dynamically resolved Class</span></span><br><span class="line">      <span class="comment">// which cannot be stored in the shared merged bean definition.</span></span><br><span class="line">      Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);</span><br><span class="line">      <span class="keyword">if</span> (resolvedClass != <span class="keyword">null</span> &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != <span class="keyword">null</span>) &#123;</span><br><span class="line">         mbdToUse = <span class="keyword">new</span> RootBeanDefinition(mbd);</span><br><span class="line">         mbdToUse.setBeanClass(resolvedClass);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Prepare method overrides.</span></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         mbdToUse.prepareMethodOverrides();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(mbdToUse.getResourceDescription(),</span><br><span class="line">               beanName, <span class="string">&quot;Validation of method overrides failed&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">// 提前给我们一个机会，去返回组件的代理对象。 Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.</span></span><br><span class="line">         Object bean = resolveBeforeInstantiation(beanName, mbdToUse);</span><br><span class="line">         <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> bean;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbdToUse.getResourceDescription(), beanName,</span><br><span class="line">               <span class="string">&quot;BeanPostProcessor before instantiation of bean failed&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123; <span class="comment">//Spring真正自己创建对象</span></span><br><span class="line">         Object beanInstance = doCreateBean(beanName, mbdToUse, args);</span><br><span class="line">         <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(<span class="string">&quot;Finished creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">return</span> beanInstance;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (BeanCreationException | ImplicitlyAppearedSingletonException ex) &#123;</span><br><span class="line">         <span class="comment">// A previously detected exception with proper bean creation context already,</span></span><br><span class="line">         <span class="comment">// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.</span></span><br><span class="line">         <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">               mbdToUse.getResourceDescription(), beanName, <span class="string">&quot;Unexpected exception during bean creation&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">resolveBeforeInstantiation</span><span class="params">(String beanName, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">	Object bean = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) &#123;</span><br><span class="line">		<span class="comment">// Make sure bean class is actually resolved at this point.</span></span><br><span class="line">		<span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">			Class&lt;?&gt; targetType = determineTargetType(beanName, mbd);</span><br><span class="line">			<span class="keyword">if</span> (targetType != <span class="keyword">null</span>) &#123;</span><br><span class="line">				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);</span><br><span class="line">				<span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		mbd.beforeInstantiationResolved = (bean != <span class="keyword">null</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">applyBeanPostProcessorsBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">		Object result = bp.postProcessBeforeInstantiation(beanClass, beanName); <span class="comment">//还是老样子，调用我们自己写的InstantiationAwareBeanPostProcessor</span></span><br><span class="line">		<span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="此方法能做什么？-1"><a href="#此方法能做什么？-1" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><p>后置处理器在此处提前给我们一个机会，去返回组件的代理对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName); <span class="comment">//if(class.isAssFrom(Cat.class))&#123;return new Dog()&#125;</span></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">null</span>; <span class="comment">//如果我们自己创建了对象返回。Spring则不会帮我们创建对象，用我们自己创建的对象（可以是代理对象）</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="SmartInstantiationAwareBeanPostProcessor-执行determineCandidateConstructors方法"><a href="#SmartInstantiationAwareBeanPostProcessor-执行determineCandidateConstructors方法" class="headerlink" title="SmartInstantiationAwareBeanPostProcessor-执行determineCandidateConstructors方法"></a>SmartInstantiationAwareBeanPostProcessor-执行determineCandidateConstructors方法</h3><h4 id="Debug调用栈-3"><a href="#Debug调用栈-3" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929174424136.png"/>

<blockquote>
<p>前面还是一样的执行逻辑，直接来到下面</p>
</blockquote>
<h4 id="AbstractAutowireCapableBeanFactory-doCreateBean-无参构造创建Bean，属性赋值，初始化等"><a href="#AbstractAutowireCapableBeanFactory-doCreateBean-无参构造创建Bean，属性赋值，初始化等" class="headerlink" title="AbstractAutowireCapableBeanFactory#doCreateBean()无参构造创建Bean，属性赋值，初始化等"></a>AbstractAutowireCapableBeanFactory#doCreateBean()无参构造创建Bean，属性赋值，初始化等</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Instantiate the bean.</span></span><br><span class="line">	BeanWrapper instanceWrapper = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (mbd.isSingleton()) &#123; <span class="comment">//是否单例的</span></span><br><span class="line">		instanceWrapper = <span class="keyword">this</span>.factoryBeanInstanceCache.remove(beanName);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (instanceWrapper == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="comment">//创建Bean的实例,默认使用无参构造器创建的对象，组件的原始对象就创建了</span></span><br><span class="line">		instanceWrapper = createBeanInstance(beanName, mbd, args);</span><br><span class="line">	&#125;</span><br><span class="line">	Object bean = instanceWrapper.getWrappedInstance();</span><br><span class="line">	Class&lt;?&gt; beanType = instanceWrapper.getWrappedClass();</span><br><span class="line">	<span class="keyword">if</span> (beanType != NullBean.class) &#123;</span><br><span class="line">		mbd.resolvedTargetType = beanType;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//允许 后置处理器 再来修改下beanDefinition；MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition；；   Allow post-processors to modify the merged bean definition.</span></span><br><span class="line">	<span class="keyword">synchronized</span> (mbd.postProcessingLock) &#123;</span><br><span class="line">		<span class="keyword">if</span> (!mbd.postProcessed) &#123;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">				<span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName,</span><br><span class="line">						<span class="string">&quot;Post-processing of merged bean definition failed&quot;</span>, ex);</span><br><span class="line">			&#125;</span><br><span class="line">			mbd.postProcessed = <span class="keyword">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Eagerly cache singletons to be able to resolve circular references</span></span><br><span class="line">	<span class="comment">// even when triggered by lifecycle interfaces like BeanFactoryAware.</span></span><br><span class="line">	<span class="keyword">boolean</span> earlySingletonExposure = (mbd.isSingleton() &amp;&amp; <span class="keyword">this</span>.allowCircularReferences &amp;&amp;</span><br><span class="line">			isSingletonCurrentlyInCreation(beanName));</span><br><span class="line">	<span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">		<span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">			logger.trace(<span class="string">&quot;Eagerly caching bean &#x27;&quot;</span> + beanName +</span><br><span class="line">					<span class="string">&quot;&#x27; to allow for resolving potential circular references&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Initialize the bean instance.</span></span><br><span class="line">	Object exposedObject = bean;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		populateBean(beanName, mbd, instanceWrapper); <span class="comment">//给创建好的对象每个属性进行赋值，@Autowired发生在这里</span></span><br><span class="line">		exposedObject = initializeBean(beanName, exposedObject, mbd);<span class="comment">//初始化bean</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line">	<span class="keyword">return</span> exposedObject;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="AbstractAutowireCapableBeanFactory-createBeanInstance-使用构造器创建Bean"><a href="#AbstractAutowireCapableBeanFactory-createBeanInstance-使用构造器创建Bean" class="headerlink" title="AbstractAutowireCapableBeanFactory#createBeanInstance()使用构造器创建Bean"></a>AbstractAutowireCapableBeanFactory#createBeanInstance()使用构造器创建Bean</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> BeanWrapper <span class="title">createBeanInstance</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span> </span>&#123;</span><br><span class="line">	<span class="comment">//获取Bean的类型  Make sure bean class is actually resolved at this point.</span></span><br><span class="line">	Class&lt;?&gt; beanClass = resolveBeanClass(mbd, beanName);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (beanClass != <span class="keyword">null</span> &amp;&amp; !Modifier.isPublic(beanClass.getModifiers()) &amp;&amp; !mbd.isNonPublicAccessAllowed()) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName,</span><br><span class="line">				<span class="string">&quot;Bean class isn&#x27;t public, and non-public access not allowed: &quot;</span> + beanClass.getName());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//定义Bean的实例提供者</span></span><br><span class="line">	Supplier&lt;?&gt; instanceSupplier = mbd.getInstanceSupplier();</span><br><span class="line">	<span class="keyword">if</span> (instanceSupplier != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> obtainFromSupplier(instanceSupplier, beanName);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//@Bean注解等可能会调用此方法进行创建出来，Spring把@Bean标注的方法理解为工厂方法</span></span><br><span class="line">	<span class="keyword">if</span> (mbd.getFactoryMethodName() != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> instantiateUsingFactoryMethod(beanName, mbd, args);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//快速创建？ Shortcut when re-creating the same bean...</span></span><br><span class="line">	<span class="keyword">boolean</span> resolved = <span class="keyword">false</span>;</span><br><span class="line">	<span class="keyword">boolean</span> autowireNecessary = <span class="keyword">false</span>;</span><br><span class="line">	<span class="keyword">if</span> (args == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">synchronized</span> (mbd.constructorArgumentLock) &#123;</span><br><span class="line">			<span class="keyword">if</span> (mbd.resolvedConstructorOrFactoryMethod != <span class="keyword">null</span>) &#123;</span><br><span class="line">				resolved = <span class="keyword">true</span>;</span><br><span class="line">				autowireNecessary = mbd.constructorArgumentsResolved;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (resolved) &#123;</span><br><span class="line">		<span class="keyword">if</span> (autowireNecessary) &#123;</span><br><span class="line">			<span class="keyword">return</span> autowireConstructor(beanName, mbd, <span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> instantiateBean(beanName, mbd);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//后置处理器有机会在这里决定当前bean用哪个构造器？SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()   Candidate constructors for autowiring?</span></span><br><span class="line">	Constructor&lt;?&gt;[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);</span><br><span class="line">	<span class="keyword">if</span> (ctors != <span class="keyword">null</span> || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||</span><br><span class="line">			mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) &#123;</span><br><span class="line">		<span class="keyword">return</span> autowireConstructor(beanName, mbd, ctors, args); <span class="comment">//构造器方式的自动注入与对象创建</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//使用默认的自己设置的高优先级的构造器  Preferred constructors for default construction?</span></span><br><span class="line">	ctors = mbd.getPreferredConstructors();</span><br><span class="line">	<span class="keyword">if</span> (ctors != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> autowireConstructor(beanName, mbd, ctors, <span class="keyword">null</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 默认使用无参构造器为当前组件创建对象；No special handling: simply use no-arg constructor.</span></span><br><span class="line">	<span class="keyword">return</span> instantiateBean(beanName, mbd);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="keyword">protected</span> Constructor&lt;?&gt;[] determineConstructorsFromBeanPostProcessors(<span class="meta">@Nullable</span> Class&lt;?&gt; beanClass, String beanName)</span><br><span class="line">		<span class="keyword">throws</span> BeansException &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (beanClass != <span class="keyword">null</span> &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">		<span class="keyword">for</span> (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) &#123;</span><br><span class="line">			Constructor&lt;?&gt;[] ctors = bp.determineCandidateConstructors(beanClass, beanName);<span class="comment">// 一样的，调我们自定义的</span></span><br><span class="line">			<span class="keyword">if</span> (ctors != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span> ctors;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol>
<li>实例提供者：</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210929175511913.png" >



<h4 id="此方法能做什么？-2"><a href="#此方法能做什么？-2" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><p>后置处理器有机会在这里决定当前bean用哪个构造器</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//返回我们要使用的构造器候选列表</span></span><br><span class="line"><span class="keyword">public</span> Constructor&lt;?&gt;[] determineCandidateConstructors(Class&lt;?&gt; beanClass, String beanName)</span><br><span class="line">      <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=&gt;&quot;</span> + beanClass + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">   <span class="comment">//返回一个我们指定的构造器</span></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="Cat-执行无参构造方法"><a href="#Cat-执行无参构造方法" class="headerlink" title="Cat-执行无参构造方法"></a>Cat-执行无参构造方法</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930110158555.png" />



<p>以前讲过。</p>
<h3 id="MergedBeanDefinitionPostProcessor-执行postProcessMergedBeanDefinition方法"><a href="#MergedBeanDefinitionPostProcessor-执行postProcessMergedBeanDefinition方法" class="headerlink" title="MergedBeanDefinitionPostProcessor-执行postProcessMergedBeanDefinition方法"></a>MergedBeanDefinitionPostProcessor-执行postProcessMergedBeanDefinition方法</h3><h4 id="Debug调用栈-4"><a href="#Debug调用栈-4" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930110913527.png" />





<h4 id="此方法能做什么？-3"><a href="#此方法能做什么？-3" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><p>看这个传进来的参数，应该就是能修改下beanDefinition</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessMergedBeanDefinition</span><span class="params">(RootBeanDefinition beanDefinition, Class&lt;?&gt; beanType, String beanName)</span> </span>&#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=&gt;&quot;</span> + beanName + <span class="string">&quot;--&quot;</span> + beanType + <span class="string">&quot;---&quot;</span> + beanDefinition);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="InstantiationAwareBeanPostProcessor-执行postProcessAfterInstantiation方法"><a href="#InstantiationAwareBeanPostProcessor-执行postProcessAfterInstantiation方法" class="headerlink" title="InstantiationAwareBeanPostProcessor-执行postProcessAfterInstantiation方法"></a>InstantiationAwareBeanPostProcessor-执行postProcessAfterInstantiation方法</h3><h4 id="Debug调用栈-5"><a href="#Debug调用栈-5" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930112247246.png"/>

<h4 id="AbstractAutowireCapableBeanFactory-populateBean-属性赋值"><a href="#AbstractAutowireCapableBeanFactory-populateBean-属性赋值" class="headerlink" title="AbstractAutowireCapableBeanFactory#populateBean()属性赋值"></a>AbstractAutowireCapableBeanFactory#populateBean()属性赋值</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">populateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> BeanWrapper bw)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (bw == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">if</span> (mbd.hasPropertyValues()) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">					mbd.getResourceDescription(), beanName, <span class="string">&quot;Cannot apply property values to null instance&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// Skip property population phase for null instance.</span></span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// @Autowired赋值也在这里(但是没做事)。可以中断初始化行为； 在属性赋值之前，后置处理器可以提前准备些东西 Give any InstantiationAwareBeanPostProcessors the opportunity to modify the</span></span><br><span class="line">	<span class="comment">// state of the bean before properties are set. This can be used, for example,</span></span><br><span class="line">	<span class="comment">// to support styles of field injection.</span></span><br><span class="line">	<span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">		<span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">			<span class="keyword">if</span> (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) &#123;</span><br><span class="line">				<span class="keyword">return</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="comment">//以上的后置处理器可以中断以下的行为</span></span><br><span class="line"></span><br><span class="line">	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">int</span> resolvedAutowireMode = mbd.getResolvedAutowireMode();</span><br><span class="line">	<span class="keyword">if</span> (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) &#123;</span><br><span class="line">		MutablePropertyValues newPvs = <span class="keyword">new</span> MutablePropertyValues(pvs);</span><br><span class="line">		<span class="comment">// Add property values based on autowire by name if applicable.</span></span><br><span class="line">		<span class="keyword">if</span> (resolvedAutowireMode == AUTOWIRE_BY_NAME) &#123;</span><br><span class="line">			autowireByName(beanName, mbd, bw, newPvs);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// Add property values based on autowire by type if applicable.</span></span><br><span class="line">		<span class="keyword">if</span> (resolvedAutowireMode == AUTOWIRE_BY_TYPE) &#123;</span><br><span class="line">			autowireByType(beanName, mbd, bw, newPvs);</span><br><span class="line">		&#125;</span><br><span class="line">		pvs = newPvs;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">boolean</span> hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();</span><br><span class="line">	<span class="keyword">boolean</span> needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);</span><br><span class="line"></span><br><span class="line">	PropertyDescriptor[] filteredPds = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (hasInstAwareBpps) &#123;</span><br><span class="line">		<span class="keyword">if</span> (pvs == <span class="keyword">null</span>) &#123;</span><br><span class="line">			pvs = mbd.getPropertyValues(); <span class="comment">//xml中property标签指定的</span></span><br><span class="line">		&#125; <span class="comment">//使用后置处理器处理属性</span></span><br><span class="line">		<span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">			PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);</span><br><span class="line">			<span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">if</span> (filteredPds == <span class="keyword">null</span>) &#123;</span><br><span class="line">					filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">				&#125;</span><br><span class="line">				pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);</span><br><span class="line">				<span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			pvs = pvsToUse; <span class="comment">//封装了当前bean的所有属性名和值，可以由后置处理器处理得到</span></span><br><span class="line">		&#125;</span><br><span class="line">           <span class="comment">// 在这里设置过的属性，在后面就不用处理了</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (needsDepCheck) &#123;</span><br><span class="line">		<span class="keyword">if</span> (filteredPds == <span class="keyword">null</span>) &#123;</span><br><span class="line">			filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">		&#125;</span><br><span class="line">		checkDependencies(beanName, mbd, filteredPds, pvs);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (pvs != <span class="keyword">null</span>) &#123; <span class="comment">//把以前处理好的PropertyValues给bean里面设置一下。主要是上面步骤没有给bean里面设置的属性</span></span><br><span class="line">		applyPropertyValues(beanName, mbd, bw, pvs); <span class="comment">//xml版的所有配置会来到这里给属性赋值</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930112621989.png"/>



<p>AutowiredAnnotationBeanPostProcessor（处理@Autowire）也在这里,但是直接返回了true，相当于没做事。</p>
<h4 id="BeanWrapperImpl-setValue"><a href="#BeanWrapperImpl-setValue" class="headerlink" title="BeanWrapperImpl#setValue()"></a>BeanWrapperImpl#setValue()</h4><p><code>applyPropertyValues(beanName, mbd, bw, pvs);</code>最终也是用下面的反射进行赋值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>  <span class="comment">//利用set方法反射赋值</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(<span class="meta">@Nullable</span> Object value)</span> <span class="keyword">throws</span> Exception </span>&#123; <span class="comment">//name  setName</span></span><br><span class="line">   Method writeMethod = (<span class="keyword">this</span>.pd <span class="keyword">instanceof</span> GenericTypeAwarePropertyDescriptor ?</span><br><span class="line">         ((GenericTypeAwarePropertyDescriptor) <span class="keyword">this</span>.pd).getWriteMethodForActualAccess() :</span><br><span class="line">         <span class="keyword">this</span>.pd.getWriteMethod());</span><br><span class="line">   <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">      AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;</span><br><span class="line">         ReflectionUtils.makeAccessible(writeMethod);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125;);</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         AccessController.doPrivileged((PrivilegedExceptionAction&lt;Object&gt;)</span><br><span class="line">               () -&gt; writeMethod.invoke(getWrappedInstance(), value), acc);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (PrivilegedActionException ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> ex.getException();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      ReflectionUtils.makeAccessible(writeMethod);</span><br><span class="line">      writeMethod.invoke(getWrappedInstance(), value);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="此方法能做什么？-4"><a href="#此方法能做什么？-4" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">postProcessAfterInstantiation</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="comment">//提前改变一些你不想让Spring管理的bean里面的属性</span></span><br><span class="line">   System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName); </span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">true</span>; <span class="comment">//返回false则bean的赋值全部结束</span></span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>

<p>这个有点类似于拦截器链，可以中断后面的行为。我感觉也没干啥事，可能我没用到过。</p>
<h3 id="InstantiationAwareBeanPostProcessor-执行postProcessProperties方法"><a href="#InstantiationAwareBeanPostProcessor-执行postProcessProperties方法" class="headerlink" title="InstantiationAwareBeanPostProcessor-执行postProcessProperties方法"></a>InstantiationAwareBeanPostProcessor-执行postProcessProperties方法</h3><h4 id="Debug调用栈-6"><a href="#Debug调用栈-6" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930113459713.png"/>



<p>和上面一样</p>
<h4 id="AutowiredAnnotationBeanPostProcessor-postProcessProperties"><a href="#AutowiredAnnotationBeanPostProcessor-postProcessProperties" class="headerlink" title="AutowiredAnnotationBeanPostProcessor#postProcessProperties()"></a>AutowiredAnnotationBeanPostProcessor#postProcessProperties()</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930114234547.png"  />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);<span class="comment">//找到自动装配的元信息</span></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      metadata.inject(bean, beanName, pvs);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanCreationException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(beanName, <span class="string">&quot;Injection of autowired dependencies failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> pvs;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AutowiredAnnotationBeanPostProcessor-findAutowiringMetadata-找到自动装配的元信息，比如-Autowired，-Value"><a href="#AutowiredAnnotationBeanPostProcessor-findAutowiringMetadata-找到自动装配的元信息，比如-Autowired，-Value" class="headerlink" title="AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata()找到自动装配的元信息，比如@Autowired，@Value"></a>AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata()找到自动装配的元信息，比如@Autowired，@Value</h4><p>自动装配处理器在这里开始真正做事</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">private</span> InjectionMetadata <span class="title">findAutowiringMetadata</span><span class="params">(String beanName, Class&lt;?&gt; clazz, <span class="meta">@Nullable</span> PropertyValues pvs)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// Fall back to class name as cache key, for backwards compatibility with custom callers.</span></span><br><span class="line">      String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());</span><br><span class="line">      <span class="comment">// Quick check on the concurrent map first, with minimal locking.</span></span><br><span class="line">      InjectionMetadata metadata = <span class="keyword">this</span>.injectionMetadataCache.get(cacheKey);</span><br><span class="line">      <span class="keyword">if</span> (InjectionMetadata.needsRefresh(metadata, clazz)) &#123;</span><br><span class="line">         <span class="keyword">synchronized</span> (<span class="keyword">this</span>.injectionMetadataCache) &#123;</span><br><span class="line">            metadata = <span class="keyword">this</span>.injectionMetadataCache.get(cacheKey);</span><br><span class="line">            <span class="keyword">if</span> (InjectionMetadata.needsRefresh(metadata, clazz)) &#123;</span><br><span class="line">               <span class="keyword">if</span> (metadata != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  metadata.clear(pvs);</span><br><span class="line">               &#125;<span class="comment">//下面是分析当前类方法或者属性有没有标注@Autowired等自动赋值的注解</span></span><br><span class="line">               metadata = buildAutowiringMetadata(clazz);</span><br><span class="line">               <span class="keyword">this</span>.injectionMetadataCache.put(cacheKey, metadata);</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> metadata;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> InjectionMetadata <span class="title">buildAutowiringMetadata</span><span class="params">(<span class="keyword">final</span> Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (!AnnotationUtils.isCandidateClass(clazz, <span class="keyword">this</span>.autowiredAnnotationTypes)) &#123;</span><br><span class="line">		<span class="keyword">return</span> InjectionMetadata.EMPTY;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	List&lt;InjectionMetadata.InjectedElement&gt; elements = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">	Class&lt;?&gt; targetClass = clazz;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">do</span> &#123;</span><br><span class="line">		<span class="keyword">final</span> List&lt;InjectionMetadata.InjectedElement&gt; currElements = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">           <span class="comment">//找所有属性中标注了@Autowired\@Value\@Inject注解</span></span><br><span class="line">		ReflectionUtils.doWithLocalFields(targetClass, field -&gt; &#123;</span><br><span class="line">			MergedAnnotation&lt;?&gt; ann = findAutowiredAnnotation(field);</span><br><span class="line">			<span class="keyword">if</span> (ann != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">if</span> (Modifier.isStatic(field.getModifiers())) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation is not supported on static fields: &quot;</span> + field);</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">boolean</span> required = determineRequiredStatus(ann);</span><br><span class="line">				currElements.add(<span class="keyword">new</span> AutowiredFieldElement(field, required));</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		<span class="comment">//拿到所有方法，看有没有@Autowired注解</span></span><br><span class="line">		ReflectionUtils.doWithLocalMethods(targetClass, method -&gt; &#123;</span><br><span class="line">			Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);</span><br><span class="line">			<span class="keyword">if</span> (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) &#123;</span><br><span class="line">				<span class="keyword">return</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			MergedAnnotation&lt;?&gt; ann = findAutowiredAnnotation(bridgedMethod);</span><br><span class="line">			<span class="keyword">if</span> (ann != <span class="keyword">null</span> &amp;&amp; method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) &#123;</span><br><span class="line">				<span class="keyword">if</span> (Modifier.isStatic(method.getModifiers())) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation is not supported on static methods: &quot;</span> + method);</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">if</span> (method.getParameterCount() == <span class="number">0</span>) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation should only be used on methods with parameters: &quot;</span> +</span><br><span class="line">								method);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">boolean</span> required = determineRequiredStatus(ann);</span><br><span class="line">				PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);</span><br><span class="line">				currElements.add(<span class="keyword">new</span> AutowiredMethodElement(method, required, pd));</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line"></span><br><span class="line">		elements.addAll(<span class="number">0</span>, currElements);</span><br><span class="line">		targetClass = targetClass.getSuperclass();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (targetClass != <span class="keyword">null</span> &amp;&amp; targetClass != Object.class);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> InjectionMetadata.forElements(elements, clazz);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="此方法能做什么？-5"><a href="#此方法能做什么？-5" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><p>这里是真正的控制属性赋值的地方</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="comment">//可以在这里解析自定义注解进行属性值注入；pvs 封装了所有的属性信息。</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span></span></span><br><span class="line"><span class="function">       <span class="keyword">throws</span> BeansException </span>&#123; </span><br><span class="line">    System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessProperties=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h3 id="Cat-执行setName-Autowire注入原理"><a href="#Cat-执行setName-Autowire注入原理" class="headerlink" title="Cat-执行setName-@Autowire注入原理"></a>Cat-执行setName-@Autowire注入原理</h3><h4 id="Debug调用栈-7"><a href="#Debug调用栈-7" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930114612277.png"/>

<p>这也说明了，@Autowire,@Value赋值的时候会去找setXXX,这也是@Autowire的原理</p>
<h4 id="AutowiredAnnotationBeanPostProcessor"><a href="#AutowiredAnnotationBeanPostProcessor" class="headerlink" title="AutowiredAnnotationBeanPostProcessor"></a>AutowiredAnnotationBeanPostProcessor</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);<span class="comment">//找到自动装配的元信息</span></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      metadata.inject(bean, beanName, pvs); </span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanCreationException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(beanName, <span class="string">&quot;Injection of autowired dependencies failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> pvs;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="BeanPostProcessor-执行postProcessBeforeInitialization方法"><a href="#BeanPostProcessor-执行postProcessBeforeInitialization方法" class="headerlink" title="BeanPostProcessor-执行postProcessBeforeInitialization方法"></a>BeanPostProcessor-执行postProcessBeforeInitialization方法</h3><h4 id="Debug调用栈-8"><a href="#Debug调用栈-8" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930143504497.png"/>







<h4 id="AbstractAutowireCapableBeanFactory-initializeBean-初始化Bean"><a href="#AbstractAutowireCapableBeanFactory-initializeBean-初始化Bean" class="headerlink" title="AbstractAutowireCapableBeanFactory#initializeBean()初始化Bean"></a>AbstractAutowireCapableBeanFactory#initializeBean()初始化Bean</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">initializeBean</span><span class="params">(String beanName, Object bean, <span class="meta">@Nullable</span> RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">         AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;</span><br><span class="line">            invokeAwareMethods(beanName, bean);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">         &#125;, getAccessControlContext());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         invokeAwareMethods(beanName, bean); <span class="comment">//组件有Aware接口，先Aware;BeanNameAware、BeanClassLoaderAware、BeanFactoryAware</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      Object wrappedBean = bean;</span><br><span class="line">      <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123;<span class="comment">//执行后置处理器的BeforeInitialization方法</span></span><br><span class="line">         wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         invokeInitMethods(beanName, wrappedBean, mbd); <span class="comment">//这里是真正初始化</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">               (mbd != <span class="keyword">null</span> ? mbd.getResourceDescription() : <span class="keyword">null</span>),</span><br><span class="line">               beanName, <span class="string">&quot;Invocation of init method failed&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123; <span class="comment">//执行后置处理器的AfterInitialization方法</span></span><br><span class="line">         wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> wrappedBean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">invokeAwareMethods</span><span class="params">(String beanName, Object bean)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> Aware) &#123;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanNameAware) &#123;</span><br><span class="line">			((BeanNameAware) bean).setBeanName(beanName);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanClassLoaderAware) &#123;</span><br><span class="line">			ClassLoader bcl = getBeanClassLoader();</span><br><span class="line">			<span class="keyword">if</span> (bcl != <span class="keyword">null</span>) &#123;</span><br><span class="line">				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanFactoryAware) &#123;</span><br><span class="line">			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.<span class="keyword">this</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">applyBeanPostProcessorsBeforeInitialization</span><span class="params">(Object existingBean, String beanName)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">	Object result = existingBean;</span><br><span class="line">	<span class="keyword">for</span> (BeanPostProcessor processor : getBeanPostProcessors()) &#123;</span><br><span class="line">		Object current = processor.postProcessBeforeInitialization(result, beanName);<span class="comment">//这里又是一样的逻辑，调用我们自定义的</span></span><br><span class="line">		<span class="keyword">if</span> (current == <span class="keyword">null</span>) &#123; <span class="comment">//不管null的东西</span></span><br><span class="line">			<span class="keyword">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line">		result = current; <span class="comment">//新Bean会替换以前的Bean</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="此方法能做什么？-6"><a href="#此方法能做什么？-6" class="headerlink" title="此方法能做什么？"></a>此方法能做什么？</h4><p>这里根据参数很明显可以看到又是一个可以改变Bean的地方</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MyBeanPostProcessor...postProcessBeforeInitialization...&quot;</span> + bean + <span class="string">&quot;==&gt;&quot;</span> + beanName);</span><br><span class="line">   <span class="keyword">return</span> bean; <span class="comment">// new Object();</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<h3 id="MergedBeanDefinitionPostProcessor-执行postProcessBeforeInitialization方法"><a href="#MergedBeanDefinitionPostProcessor-执行postProcessBeforeInitialization方法" class="headerlink" title="MergedBeanDefinitionPostProcessor-执行postProcessBeforeInitialization方法"></a>MergedBeanDefinitionPostProcessor-执行postProcessBeforeInitialization方法</h3><p>因为MergedBeanDefinitionPostProcessor是继承自BeanPostProcessor，所以这里的效果和BeanPostProcessor#postProcessBeforeInitialization效果一样</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">   System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=&gt;&quot;</span> + bean + <span class="string">&quot;--&quot;</span> + beanName);</span><br><span class="line">   <span class="keyword">return</span> bean; <span class="comment">//null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="Cat-调用afterPropertiesSet方法"><a href="#Cat-调用afterPropertiesSet方法" class="headerlink" title="Cat-调用afterPropertiesSet方法"></a>Cat-调用afterPropertiesSet方法</h3><h4 id="Debug调用栈-9"><a href="#Debug调用栈-9" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930150311019.png"/>





<h4 id="AbstractAutowireCapableBeanFactory-invokeInitMethods"><a href="#AbstractAutowireCapableBeanFactory-invokeInitMethods" class="headerlink" title="AbstractAutowireCapableBeanFactory#invokeInitMethods()"></a>AbstractAutowireCapableBeanFactory#invokeInitMethods()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">invokeInitMethods</span><span class="params">(String beanName, Object bean, <span class="meta">@Nullable</span> RootBeanDefinition mbd)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">       <span class="comment">//如果组件实现了 InitializingBean 接口，就调用组件自己的afterPropertiesSet</span></span><br><span class="line">   <span class="keyword">boolean</span> isInitializingBean = (bean <span class="keyword">instanceof</span> InitializingBean);</span><br><span class="line">   <span class="keyword">if</span> (isInitializingBean &amp;&amp; (mbd == <span class="keyword">null</span> || !mbd.isExternallyManagedInitMethod(<span class="string">&quot;afterPropertiesSet&quot;</span>))) &#123;</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Invoking afterPropertiesSet() on bean with name &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">            AccessController.doPrivileged((PrivilegedExceptionAction&lt;Object&gt;) () -&gt; &#123;</span><br><span class="line">               ((InitializingBean) bean).afterPropertiesSet();  <span class="comment">//调自定义的</span></span><br><span class="line">               <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;, getAccessControlContext());</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">catch</span> (PrivilegedActionException pae) &#123;</span><br><span class="line">            <span class="keyword">throw</span> pae.getException();</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         ((InitializingBean) bean).afterPropertiesSet(); <span class="comment">//调自定义的</span></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (mbd != <span class="keyword">null</span> &amp;&amp; bean.getClass() != NullBean.class) &#123;</span><br><span class="line">      String initMethodName = mbd.getInitMethodName(); <span class="comment">//如果有自定义的初始化方法，就是那个init-method，这里也会执行</span></span><br><span class="line">      <span class="keyword">if</span> (StringUtils.hasLength(initMethodName) &amp;&amp;</span><br><span class="line">            !(isInitializingBean &amp;&amp; <span class="string">&quot;afterPropertiesSet&quot;</span>.equals(initMethodName)) &amp;&amp;</span><br><span class="line">            !mbd.isExternallyManagedInitMethod(initMethodName)) &#123;</span><br><span class="line">         invokeCustomInitMethod(beanName, bean, mbd);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="BeanPostProcessor-执行postProcessAfterInitialization方法"><a href="#BeanPostProcessor-执行postProcessAfterInitialization方法" class="headerlink" title="BeanPostProcessor-执行postProcessAfterInitialization方法"></a>BeanPostProcessor-执行postProcessAfterInitialization方法</h3><h4 id="Debug调用栈-10"><a href="#Debug调用栈-10" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_03/image-20210930150604716.png"/>





<h3 id="MergedBeanDefinitionPostProcessor-执行postProcessAfterInitialization方法"><a href="#MergedBeanDefinitionPostProcessor-执行postProcessAfterInitialization方法" class="headerlink" title="MergedBeanDefinitionPostProcessor-执行postProcessAfterInitialization方法"></a>MergedBeanDefinitionPostProcessor-执行postProcessAfterInitialization方法</h3><p>同上</p>
<blockquote>
<ol>
<li>至此，后置处理器处理完成了。</li>
<li>Spring内部所有的功能增强都是由后置处理器完成。例如事务，AOP，代理等等</li>
</ol>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/66c146e7.html">https://imlql.cn/post/66c146e7.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/49f419ae.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div class="next-post pull-right"><a href="/post/41fb8d9e.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC3%E7%AB%A0-%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8%E5%92%8CBean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">第3章-后置处理器和Bean生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E6%9D%A5%E7%9C%8B%E4%B8%80%E4%B8%8B%E6%88%91%E4%BB%AC%E7%9A%84%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">再来看一下我们的测试类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanPostProcessor"><span class="toc-text">MyBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyInstantiationAwareBeanPostProcessor"><span class="toc-text">MyInstantiationAwareBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyMergedBeanDefinitionPostProcessor"><span class="toc-text">MyMergedBeanDefinitionPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MySmartInstantiationAwareBeanPostProcessor"><span class="toc-text">MySmartInstantiationAwareBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanFactoryPostProcessor"><span class="toc-text">MyBeanFactoryPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanDefinitionRegistryPostProcessor"><span class="toc-text">MyBeanDefinitionRegistryPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cat"><span class="toc-text">Cat</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#beans2-xml"><span class="toc-text">beans2.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MainTest"><span class="toc-text">MainTest</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E7%BB%ADBean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">继续Bean生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-Bean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E4%B8%8E%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">流程图-Bean生命周期与后置处理器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanPostProcessor-%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">BeanPostProcessor-执行无参构造</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext-registerBeanPostProcessors-%E6%B3%A8%E5%86%8CBean%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">AbstractApplicationContext#registerBeanPostProcessors()注册Bean后置处理器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PostProcessorRegistrationDelegate-registerBeanPostProcessors"><span class="toc-text">PostProcessorRegistrationDelegate#registerBeanPostProcessors()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">InstantiationAwareBeanPostProcessor-执行无参构造</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MergedBeanDefinitionPostProcessor-%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">MergedBeanDefinitionPostProcessor-执行无参构造</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SmartInstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">SmartInstantiationAwareBeanPostProcessor-执行无参构造</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SmartInstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8CpredictBeanType%E6%96%B9%E6%B3%95"><span class="toc-text">SmartInstantiationAwareBeanPostProcessor-执行predictBeanType方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-1"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext-refresh"><span class="toc-text">AbstractApplicationContext#refresh()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultListableBeanFactory-doGetBeanNamesForType-%E8%8E%B7%E5%8F%96%E6%9F%90%E4%B8%80%E4%B8%AA%E7%BB%84%E4%BB%B6%E5%9C%A8%E5%AE%B9%E5%99%A8%E4%B8%AD%E7%9A%84%E5%90%8D%E5%AD%97"><span class="toc-text">DefaultListableBeanFactory#doGetBeanNamesForType()获取某一个组件在容器中的名字</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractBeanFactory-isTypeMatch"><span class="toc-text">AbstractBeanFactory#isTypeMatch()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-predictBeanType"><span class="toc-text">AbstractAutowireCapableBeanFactory#predictBeanType()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8CpostProcessBeforeInstantiation%E6%96%B9%E6%B3%95"><span class="toc-text">InstantiationAwareBeanPostProcessor-执行postProcessBeforeInstantiation方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-2"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext-finishBeanFactoryInitialization-%E5%AE%8C%E6%88%90BeanFactory%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">AbstractApplicationContext#finishBeanFactoryInitialization()完成BeanFactory初始化</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-createBean-%E5%88%9B%E5%BB%BABean"><span class="toc-text">AbstractAutowireCapableBeanFactory#createBean()创建Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-1"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SmartInstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8CdetermineCandidateConstructors%E6%96%B9%E6%B3%95"><span class="toc-text">SmartInstantiationAwareBeanPostProcessor-执行determineCandidateConstructors方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-3"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-doCreateBean-%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0%E5%88%9B%E5%BB%BABean%EF%BC%8C%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC%EF%BC%8C%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AD%89"><span class="toc-text">AbstractAutowireCapableBeanFactory#doCreateBean()无参构造创建Bean，属性赋值，初始化等</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-createBeanInstance-%E4%BD%BF%E7%94%A8%E6%9E%84%E9%80%A0%E5%99%A8%E5%88%9B%E5%BB%BABean"><span class="toc-text">AbstractAutowireCapableBeanFactory#createBeanInstance()使用构造器创建Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-2"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cat-%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="toc-text">Cat-执行无参构造方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MergedBeanDefinitionPostProcessor-%E6%89%A7%E8%A1%8CpostProcessMergedBeanDefinition%E6%96%B9%E6%B3%95"><span class="toc-text">MergedBeanDefinitionPostProcessor-执行postProcessMergedBeanDefinition方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-4"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-3"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8CpostProcessAfterInstantiation%E6%96%B9%E6%B3%95"><span class="toc-text">InstantiationAwareBeanPostProcessor-执行postProcessAfterInstantiation方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-5"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-populateBean-%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC"><span class="toc-text">AbstractAutowireCapableBeanFactory#populateBean()属性赋值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanWrapperImpl-setValue"><span class="toc-text">BeanWrapperImpl#setValue()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-4"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InstantiationAwareBeanPostProcessor-%E6%89%A7%E8%A1%8CpostProcessProperties%E6%96%B9%E6%B3%95"><span class="toc-text">InstantiationAwareBeanPostProcessor-执行postProcessProperties方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-6"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AutowiredAnnotationBeanPostProcessor-postProcessProperties"><span class="toc-text">AutowiredAnnotationBeanPostProcessor#postProcessProperties()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AutowiredAnnotationBeanPostProcessor-findAutowiringMetadata-%E6%89%BE%E5%88%B0%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D%E7%9A%84%E5%85%83%E4%BF%A1%E6%81%AF%EF%BC%8C%E6%AF%94%E5%A6%82-Autowired%EF%BC%8C-Value"><span class="toc-text">AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata()找到自动装配的元信息，比如@Autowired，@Value</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-5"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cat-%E6%89%A7%E8%A1%8CsetName-Autowire%E6%B3%A8%E5%85%A5%E5%8E%9F%E7%90%86"><span class="toc-text">Cat-执行setName-@Autowire注入原理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-7"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AutowiredAnnotationBeanPostProcessor"><span class="toc-text">AutowiredAnnotationBeanPostProcessor</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanPostProcessor-%E6%89%A7%E8%A1%8CpostProcessBeforeInitialization%E6%96%B9%E6%B3%95"><span class="toc-text">BeanPostProcessor-执行postProcessBeforeInitialization方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-8"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-initializeBean-%E5%88%9D%E5%A7%8B%E5%8C%96Bean"><span class="toc-text">AbstractAutowireCapableBeanFactory#initializeBean()初始化Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AD%A4%E6%96%B9%E6%B3%95%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F-6"><span class="toc-text">此方法能做什么？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MergedBeanDefinitionPostProcessor-%E6%89%A7%E8%A1%8CpostProcessBeforeInitialization%E6%96%B9%E6%B3%95"><span class="toc-text">MergedBeanDefinitionPostProcessor-执行postProcessBeforeInitialization方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cat-%E8%B0%83%E7%94%A8afterPropertiesSet%E6%96%B9%E6%B3%95"><span class="toc-text">Cat-调用afterPropertiesSet方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-9"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-invokeInitMethods"><span class="toc-text">AbstractAutowireCapableBeanFactory#invokeInitMethods()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanPostProcessor-%E6%89%A7%E8%A1%8CpostProcessAfterInitialization%E6%96%B9%E6%B3%95"><span class="toc-text">BeanPostProcessor-执行postProcessAfterInitialization方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-10"><span class="toc-text">Debug调用栈</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MergedBeanDefinitionPostProcessor-%E6%89%A7%E8%A1%8CpostProcessAfterInitialization%E6%96%B9%E6%B3%95"><span class="toc-text">MergedBeanDefinitionPostProcessor-执行postProcessAfterInitialization方法</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>